package org.fluidripple.socket.session;

import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 存储客户端会话信息，主要目的是：有时会在web端直接下发某种指令，所以要有个地方用来维护会话信息得
 */
@Slf4j
public class SessionStore {

    //session存储集合，key：设备编号，value：Session对象
    private final ConcurrentHashMap<String, Session> sessionMap = new ConcurrentHashMap<>();
    private Collection<Session> sessionList = new ArrayList<>();
    /**
     * 存储会话
     */
    public void storeSession(String deviceNo, Session session) {

        if (StringUtils.hasLength(deviceNo)&&!sessionMap.containsKey(deviceNo)) {
            log.info("=>设备[{}]本地会话注册",session.getDeviceSerializable());
            sessionMap.put(deviceNo, session);
        }
        if (!sessionList.contains(session)){
            sessionList.add(session);
        }
    }

    /**
     * 获取会话
     */
    public Session getSession(String deviceNo) {
        return sessionMap.get(deviceNo);
    }



    public Session getSessionIp(String ip) {
        Optional<Session> any = sessionList.stream().filter(v -> v.getRemoteAddressStr().equals(ip)).findAny();
        return any.isPresent() ? any.get() : null;
    }

    /**
     * 删除会话
     */
    public Session removeSession(Session session) {
        String deviceNo = session.getDeviceSerializable();
        if (StringUtils.hasLength(deviceNo)){
            sessionMap.remove(deviceNo);
        }
        boolean remove = sessionList.remove(session);
        log.info("当前session是否删除成功：{}",remove);
        return null;
    }

    /**
     * 判断会话是否存在
     */
    public boolean containsKey(String deviceNo) {
        return sessionMap.containsKey(deviceNo);
    }

    public Collection<Session> list() {
        return sessionList;
    }

    public List<Session> getSession(List<String> deviceNoList){
        List<Session> sessionList=new ArrayList<>();
        for (String deviceNo : deviceNoList) {
            Session session = sessionMap.get(deviceNo);
            Optional.ofNullable(session).ifPresent(v->sessionList.add(v));
        }
        return sessionList;
    }
}
